<template>
  <div class="rule-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>选宿规则管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新增规则
          </el-button>
        </div>
      </template>
      
      <el-table :data="rules" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="规则ID" width="80" />
        <el-table-column prop="ruleName" label="规则名称" width="150" />
        <el-table-column prop="ruleType" label="规则类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getRuleTypeColor(row.ruleType)">
              {{ row.ruleType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ruleContent" label="规则内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="scope" label="适用范围" width="120" />
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)">
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRule(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="rules.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无规则数据" />
      </div>
    </el-card>

    <!-- 创建/编辑规则对话框 -->
    <el-dialog 
      :title="isEdit ? '编辑规则' : '新增规则'"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="ruleForm" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        
        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="ruleForm.ruleType" placeholder="请选择规则类型" style="width: 100%">
            <el-option label="专业限制" value="专业限制" />
            <el-option label="性别限制" value="性别限制" />
            <el-option label="年级限制" value="年级限制" />
            <el-option label="时间限制" value="时间限制" />
            <el-option label="楼层限制" value="楼层限制" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="规则内容" prop="ruleContent">
          <el-input 
            v-model="ruleForm.ruleContent" 
            type="textarea" 
            :rows="3"
            placeholder="请输入具体的规则内容"
          />
        </el-form-item>
        
        <el-form-item label="适用范围" prop="scope">
          <el-select v-model="ruleForm.scope" placeholder="请选择适用范围" style="width: 100%">
            <el-option label="全校" value="全校" />
            <el-option label="东信一" value="东信一" />
            <el-option label="东信三" value="东信三" />
            <el-option label="西区一" value="西区一" />
            <el-option label="西区二" value="西区二" />
            <el-option label="南区" value="南区" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-input-number 
            v-model="ruleForm.priority" 
            :min="1" 
            :max="10" 
            placeholder="1-10，数字越大优先级越高"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="ruleForm.description" 
            type="textarea" 
            :rows="2"
            placeholder="规则描述（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'

const rules = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()

const ruleForm = reactive({
  id: null,
  ruleName: '',
  ruleType: '',
  ruleContent: '',
  scope: '',
  priority: 1,
  description: ''
})

const formRules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  ruleContent: [
    { required: true, message: '请输入规则内容', trigger: 'blur' }
  ],
  scope: [
    { required: true, message: '请选择适用范围', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'change' }
  ]
}

const getRuleTypeColor = (type) => {
  const colorMap = {
    '专业限制': 'primary',
    '性别限制': 'success',
    '年级限制': 'warning',
    '时间限制': 'danger',
    '楼层限制': 'info',
    '其他': 'default'
  }
  return colorMap[type] || 'default'
}

const getPriorityColor = (priority) => {
  if (priority >= 8) return 'danger'
  if (priority >= 5) return 'warning'
  return 'success'
}

const loadRules = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/rule/list')
    if (response.data.code === 200) {
      rules.value = response.data.data
    }
  } catch (error) {
    console.error('加载规则数据失败:', error)
    ElMessage.error('加载规则数据失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  resetForm()
  Object.assign(ruleForm, row)
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(ruleForm, {
    id: null,
    ruleName: '',
    ruleType: '',
    ruleContent: '',
    scope: '',
    priority: 1,
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = isEdit.value ? '/api/rule/update' : '/api/rule/add'
        const method = isEdit.value ? 'put' : 'post'
        
        const response = await request[method](url, ruleForm)
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '规则更新成功' : '规则创建成功')
          dialogVisible.value = false
          loadRules()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const deleteRule = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则 "${row.ruleName}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(`/api/rule/delete/${row.id}`)
    if (response.data.code === 200) {
      ElMessage.success('规则删除成功')
      loadRules()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadRules()
})
</script>

<style scoped>
.rule-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>